<?php

class Projects extends Model {

	var $PROJECT_IN_PROGRESS = 1;
	var $PROJECT_DONE = 2;

	function Projects() {
		parent::Model();
	}

	function create( $title, $description, $status = false ) {
		if( $status == false ) {
			$status = $this->PROJECT_IN_PROGRESS;
		}
		$sql = 'insert into `projects`(`title`,`description`, `status`)'
			.'values(?, ?, ?)';
		$this->db->query( $sql, array( $title, $description, $status ) );
	}

	function attach_account( $project_id, $account_id, $manager = false) {
		$sql = 'insert into `accounts_projects`'
			.'(`account_id`, `project_id`, `is_manager`)'
			.'values(?, ?, ?) on duplicate key update `is_manager`=?';
		$this->db->query( $sql, array( $account_id, $project_id, $manager, $manager));
	}

	function detach_account( $project_id, $account_id ) {
		$sql = 'delete from `accounts_projects` '
			.'where `project_id`=? and `account_id`=?';
		$this->db->query( $sql, array($project_id, $account_id));
	}

	function fetch( $project_id ) {
		$sql = 'select * from `projects` where `project_id`=?';
		$result = $this->db->query( $sql, array( $project_id ) );
		return $result->row();
	}

	function fetch_all($account = false) {
		$vars = array();
		$sql = 'select * from `projects`';	
		if($account != false) {
			if($account->is_admin == 0) {
				$sql = 'select p.* from `projects` p, `accounts_projects` ap ' 
					. 'where ap.account_id=? and ap.project_id = p.project_id';
				$vars[] = $account->account_id;
			}	
		}
		$r = $this->db->query($sql, $vars);

		return $r->result();
	}

	function update_status( $project_id, $status ) {
		$sql = 'update `projects` set `status`=? where `project_id`=?';
		$this->db->query( $sql, array( $status, $project_id) );	
	}

	function update( $project_id, $title, $description, $start_date, $end_date, $status ) {
		$sql = 'update `projects` set `title`=?, `description`=?, '
			.'`start_date`=?, `end_date`=?, `status`=? where `project_id`=?';
		$this->db->query( $sql, array( $title, $description, 
			$start_date, $end_date, $status, $project_id) );
	}

	function remove( $project_id ) {
		$sql = 'delete from `projects` where `project_id`=?';
		$this->db->query( $sql, array( $project_id ));
	}
}

?>
